package com.chak.voyage.crawler.pipeline;

import com.chak.voyage.data.dao.INoteDao;
import com.chak.voyage.data.entity.TNote;
import com.chak.voyage.data.entity.TNoteExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

/**
 * Created by delzh on 2016/9/4.
 */

@Component
public class Article2MySQLPipeline implements Pipeline{

    private static Logger LOG = LoggerFactory.getLogger(Article2MySQLPipeline.class);

    @Autowired
    private INoteDao iNoteDao;

    public void process(ResultItems resultItems, Task task) {
        TNote note = resultItems.get("note");
        if (note != null) {
            TNoteExample tNoteExample = new TNoteExample();
            tNoteExample.createCriteria()
                    .andTypeEqualTo(note.getType())
                    .andContentIdEqualTo(note.getContentId());
            if (iNoteDao.selectByExample(tNoteExample).isEmpty()) {
                int count = iNoteDao.insertSelective(note);
                if (count == 1) {
                    LOG.info("添加新文章成功, id:{}", note.getId());
                } else {
                    LOG.info("添加新文章失败! url:{}", note.getUrl());
                }
            }
            else {
                LOG.info("重复文章!放弃录入:{}",note);
            }
        }
    }
}
